package org.lisen.quartz.controller;

import org.lisen.quartz.quartz.PrintJobService;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @author laughing
 * @date 2020/9/29
 * @site https://www.lisen.org
 */
@RestController
public class QuartzController {

    @RequestMapping("/quartz")
    public String quartz() throws SchedulerException {
        //创建一个scheduler
        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
        //通过scheduler传参数
        scheduler.getContext().put("sKey", "sValue");
        //创建一个Trigger
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("trigger1", "group1")
                .usingJobData("t1", "tv1")
                //3秒执行一次
                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(3)
                //执行1次
                .withRepeatCount(0))
                .build();
        trigger.getJobDataMap().put("t2", "tv2");
        //创建一个job
        JobDetail job = JobBuilder.newJob(PrintJobService.class)
                .usingJobData("j1", "jv1")
                .withIdentity("myJob", "myGroup").build();
        job.getJobDataMap().put("j2", "jv2");
        //注册trigger并启动scheduler
        scheduler.scheduleJob(job, trigger);
        scheduler.start();
        return "success";
    }
}
